// Popup Script - 弹出窗口逻辑

class PopupController {
  constructor() {
    this.isRecording = false;
    this.currentTab = null;
    this.recordings = [];
    
    // DOM元素
    this.elements = {
      recordBtn: document.getElementById('recordBtn'),
      statusIndicator: document.getElementById('statusIndicator'),
      recordingsList: document.getElementById('recordingsList'),
      settingsBtn: document.getElementById('settingsBtn'),
      settingsPanel: document.getElementById('settingsPanel'),
      backBtn: document.getElementById('backBtn'),
      viewAllBtn: document.getElementById('viewAllBtn'),
      helpLink: document.getElementById('helpLink'),
      feedbackLink: document.getElementById('feedbackLink'),
      
      // 设置相关
      autoCapture: document.getElementById('autoCapture'),
      highlightElements: document.getElementById('highlightElements'),
      captureDelay: document.getElementById('captureDelay'),
      highlightColor: document.getElementById('highlightColor'),
      exportFormat: document.getElementById('exportFormat'),
      saveSettingsBtn: document.getElementById('saveSettingsBtn'),
      resetSettingsBtn: document.getElementById('resetSettingsBtn')
    };
    
    this.init();
  }
  
  async init() {
    // 获取当前标签页
    await this.getCurrentTab();
    
    // 检查录制状态
    await this.checkRecordingState();
    
    // 加载录制列表
    await this.loadRecordings();
    
    // 加载设置
    await this.loadSettings();
    
    // 设置事件监听器
    this.setupEventListeners();
  }
  
  async getCurrentTab() {
    const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
    this.currentTab = tabs[0];
  }
  
  async checkRecordingState() {
    try {
      const response = await chrome.runtime.sendMessage({ 
        action: 'GET_RECORDING_STATE' 
      });
      
      if (response.success) {
        this.isRecording = response.isRecording;
        this.updateUI();
      }
    } catch (error) {
      console.error('Failed to check recording state:', error);
    }
  }
  
  async loadRecordings() {
    try {
      const response = await chrome.runtime.sendMessage({ 
        action: 'GET_RECORDINGS' 
      });
      
      if (response.success) {
        this.recordings = response.recordings;
        this.renderRecordings();
      }
    } catch (error) {
      console.error('Failed to load recordings:', error);
    }
  }
  
  async loadSettings() {
    const settings = await chrome.storage.local.get('scribehow_settings');
    const defaultSettings = {
      autoCapture: true,
      highlightElements: true,
      captureDelay: 500,
      highlightColor: '#ff5252',
      exportFormat: 'markdown'
    };
    
    const currentSettings = { ...defaultSettings, ...(settings.scribehow_settings || {}) };
    
    // 应用设置到UI
    this.elements.autoCapture.checked = currentSettings.autoCapture;
    this.elements.highlightElements.checked = currentSettings.highlightElements;
    this.elements.captureDelay.value = currentSettings.captureDelay;
    this.elements.highlightColor.value = currentSettings.highlightColor;
    this.elements.exportFormat.value = currentSettings.exportFormat;
  }
  
  setupEventListeners() {
    // 录制按钮
    this.elements.recordBtn.addEventListener('click', () => this.toggleRecording());
    
    // 设置按钮
    this.elements.settingsBtn.addEventListener('click', () => this.showSettings());
    this.elements.backBtn.addEventListener('click', () => this.hideSettings());
    
    // 保存设置
    this.elements.saveSettingsBtn.addEventListener('click', () => this.saveSettings());
    this.elements.resetSettingsBtn.addEventListener('click', () => this.resetSettings());
    
    // 查看所有录制
    this.elements.viewAllBtn.addEventListener('click', () => this.viewAllRecordings());
    
    // 帮助和反馈链接
    this.elements.helpLink.addEventListener('click', (e) => {
      e.preventDefault();
      chrome.tabs.create({ url: 'https://github.com/yourusername/scribehow-extension/wiki' });
    });
    
    this.elements.feedbackLink.addEventListener('click', (e) => {
      e.preventDefault();
      chrome.tabs.create({ url: 'https://github.com/yourusername/scribehow-extension/issues' });
    });
  }
  
  async toggleRecording() {
    if (this.isRecording) {
      await this.stopRecording();
    } else {
      await this.startRecording();
    }
  }
  
  async startRecording() {
    try {
      const response = await chrome.runtime.sendMessage({
        action: 'START_RECORDING',
        tabId: this.currentTab.id
      });
      
      if (response.success) {
        this.isRecording = true;
        this.updateUI();
        
        // 关闭弹出窗口，让用户开始操作
        window.close();
      }
    } catch (error) {
      console.error('Failed to start recording:', error);
      this.showError('Failed to start recording. Please try again.');
    }
  }
  
  async stopRecording() {
    try {
      const response = await chrome.runtime.sendMessage({
        action: 'STOP_RECORDING'
      });
      
      if (response.success) {
        this.isRecording = false;
        this.updateUI();
        
        // 重新加载录制列表
        await this.loadRecordings();
        
        // 如果有新录制，显示导出选项
        if (response.recording) {
          this.showExportOptions(response.recording);
        }
      }
    } catch (error) {
      console.error('Failed to stop recording:', error);
      this.showError('Failed to stop recording. Please try again.');
    }
  }
  
  updateUI() {
    if (this.isRecording) {
      this.elements.recordBtn.textContent = 'Stop Recording';
      this.elements.recordBtn.classList.add('stop');
      this.elements.recordBtn.innerHTML = `
        <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
          <rect x="6" y="6" width="8" height="8" rx="2" fill="currentColor"/>
        </svg>
        Stop Recording
      `;
      
      this.elements.statusIndicator.classList.add('recording');
      this.elements.statusIndicator.querySelector('.status-text').textContent = 'Recording in progress';
    } else {
      this.elements.recordBtn.textContent = 'Start Recording';
      this.elements.recordBtn.classList.remove('stop');
      this.elements.recordBtn.innerHTML = `
        <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
          <circle cx="10" cy="10" r="8" stroke="currentColor" stroke-width="2"/>
          <circle cx="10" cy="10" r="3" fill="currentColor"/>
        </svg>
        Start Recording
      `;
      
      this.elements.statusIndicator.classList.remove('recording');
      this.elements.statusIndicator.querySelector('.status-text').textContent = 'Ready to record';
    }
  }
  
  renderRecordings() {
    const container = this.elements.recordingsList;
    
    if (this.recordings.length === 0) {
      container.innerHTML = `
        <div class="empty-state">
          <svg width="48" height="48" viewBox="0 0 48 48" fill="none">
            <rect x="8" y="8" width="32" height="32" rx="4" stroke="currentColor" stroke-width="2" stroke-dasharray="4 4"/>
            <path d="M18 24h12M24 18v12" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
          </svg>
          <p>No recordings yet</p>
          <p class="text-muted">Start recording to create your first guide</p>
        </div>
      `;
      return;
    }
    
    // 显示最近的3个录制
    const recentRecordings = this.recordings.slice(0, 3);
    
    container.innerHTML = recentRecordings.map(recording => `
      <div class="recording-item" data-id="${recording.id}">
        <div class="recording-icon">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
            <path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
          </svg>
        </div>
        <div class="recording-info">
          <div class="recording-title">${this.escapeHtml(recording.title)}</div>
          <div class="recording-meta">
            <span>${recording.steps.length} steps</span>
            <span>•</span>
            <span>${this.formatDate(recording.startTime)}</span>
          </div>
        </div>
        <div class="recording-actions">
          <button class="icon-btn" data-action="export" data-id="${recording.id}" title="Export">
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
              <path d="M8 11V3m0 0L5 6m3-3l3 3m5 2v5a1 1 0 01-1 1H1a1 1 0 01-1-1V8" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
          </button>
          <button class="icon-btn" data-action="delete" data-id="${recording.id}" title="Delete">
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
              <path d="M2 4h12M5 4V2.5A1.5 1.5 0 016.5 1h3A1.5 1.5 0 0111 2.5V4m2 0v9.5a1.5 1.5 0 01-1.5 1.5h-7A1.5 1.5 0 013 13.5V4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
          </button>
        </div>
      </div>
    `).join('');
    
    // 绑定事件
    container.querySelectorAll('[data-action]').forEach(btn => {
      btn.addEventListener('click', (e) => {
        e.stopPropagation();
        const action = btn.dataset.action;
        const id = btn.dataset.id;
        
        if (action === 'export') {
          const recording = this.recordings.find(r => r.id === id);
          this.exportRecording(recording);
        } else if (action === 'delete') {
          this.deleteRecording(id);
        }
      });
    });
    
    // 点击录制项查看详情
    container.querySelectorAll('.recording-item').forEach(item => {
      item.addEventListener('click', () => {
        const id = item.dataset.id;
        const recording = this.recordings.find(r => r.id === id);
        this.viewRecording(recording);
      });
    });
  }
  
  async exportRecording(recording) {
    const format = this.elements.exportFormat.value;
    
    try {
      await chrome.runtime.sendMessage({
        action: 'EXPORT_RECORDING',
        recording: recording,
        format: format,
        download: true
      });
      
      this.showSuccess('Recording exported successfully!');
    } catch (error) {
      console.error('Failed to export recording:', error);
      this.showError('Failed to export recording. Please try again.');
    }
  }
  
  async deleteRecording(recordingId) {
    if (!confirm('Are you sure you want to delete this recording?')) {
      return;
    }
    
    try {
      await chrome.runtime.sendMessage({
        action: 'DELETE_RECORDING',
        recordingId: recordingId
      });
      
      // 重新加载列表
      await this.loadRecordings();
      
      this.showSuccess('Recording deleted successfully!');
    } catch (error) {
      console.error('Failed to delete recording:', error);
      this.showError('Failed to delete recording. Please try again.');
    }
  }
  
  viewRecording(recording) {
    // 创建新标签页显示录制详情
    chrome.tabs.create({
      url: chrome.runtime.getURL(`src/viewer/viewer.html?id=${recording.id}`)
    });
  }
  
  viewAllRecordings() {
    chrome.tabs.create({
      url: chrome.runtime.getURL('src/manager/manager.html')
    });
  }
  
  showSettings() {
    this.elements.settingsPanel.style.display = 'flex';
  }
  
  hideSettings() {
    this.elements.settingsPanel.style.display = 'none';
  }
  
  async saveSettings() {
    const settings = {
      autoCapture: this.elements.autoCapture.checked,
      highlightElements: this.elements.highlightElements.checked,
      captureDelay: parseInt(this.elements.captureDelay.value),
      highlightColor: this.elements.highlightColor.value,
      exportFormat: this.elements.exportFormat.value
    };
    
    await chrome.storage.local.set({ scribehow_settings: settings });
    
    // 通知所有已打开的标签页更新设置
    try {
      const tabs = await chrome.tabs.query({});
      tabs.forEach(tab => {
        chrome.tabs.sendMessage(tab.id, { 
          action: 'UPDATE_SETTINGS' 
        }).catch(() => {
          // 忽略未注入脚本的标签页错误
        });
      });
    } catch (error) {
      console.log('Failed to update tabs settings:', error);
    }
    
    this.showSuccess('Settings saved successfully!');
    this.hideSettings();
  }
  
  async resetSettings() {
    if (!confirm('Are you sure you want to reset all settings to default?')) {
      return;
    }
    
    await chrome.storage.local.remove('scribehow_settings');
    await this.loadSettings();
    
    this.showSuccess('Settings reset to default!');
  }
  
  showExportOptions(recording) {
    // 不自动导出，只显示成功消息
    this.showSuccess(`Recording completed with ${recording.steps.length} steps!`);
    
    // 重新加载录制列表以显示新录制
    this.loadRecordings();
  }
  
  showSuccess(message) {
    this.showNotification(message, 'success');
  }
  
  showError(message) {
    this.showNotification(message, 'error');
  }
  
  showNotification(message, type) {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.textContent = message;
    
    document.body.appendChild(notification);
    
    // 3秒后移除
    setTimeout(() => {
      notification.remove();
    }, 3000);
  }
  
  formatDate(dateString) {
    const date = new Date(dateString);
    const now = new Date();
    const diff = now - date;
    
    // 如果是今天
    if (diff < 86400000 && date.getDate() === now.getDate()) {
      return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    }
    
    // 如果是昨天
    if (diff < 172800000 && date.getDate() === now.getDate() - 1) {
      return 'Yesterday';
    }
    
    // 其他情况显示日期
    return date.toLocaleDateString([], { month: 'short', day: 'numeric' });
  }
  
  escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
  }
}

// 初始化
document.addEventListener('DOMContentLoaded', () => {
  new PopupController();
});
